/*
 * @Author: your name
 * @Date: 2022-03-27 23:11:19
 * @LastEditTime: 2022-04-03 23:44:25
 * @LastEditors: Please set LastEditors
 * @Description: 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 * @FilePath: \blog_web\src\store\index.js
 */
import Vue from 'vue'
import Vuex from 'vuex'

// 导入本地存储的函数
import db from '@/util/localstorage'
Vue.use(Vuex)

// 实现模块的自动化加载
const modulesFiles = require.context('./modules', true, /\.js$/)

const modules = modulesFiles.keys().reduce((modules, modulePath) => {
  // set './app.js' => 'app'
  const moduleName = modulePath.replace(/^\.\/(.*)\.\w+$/, '$1')
  const value = modulesFiles(modulePath)
  modules[moduleName] = value.default
  return modules
}, {})

const store = new Vuex.Store({
  modules
})

// 初始化vuex
export function initStore() {
  // 防止刷新的时候vuex的数据丢失
  if (db.get('user')) {
    store.commit('user/setUser', db.get('user'))
    store.dispatch('follow/getList', {
      id: db.get('user').id
    })
  }
  // token
  if (db.get('token')) {
    store.commit('user/setToken', db.get('token'))
  }
}

export default store
